Skip to content

Map OpenAPI Discriminator mapping's values to their real value in enums #3074

Merged
koxudaxi merged 5 commits into
koxudaxi:mainfrom
ilovelinux:fix/ilovelinux-3073-enum-literal-values
May 22, 2026
Merged

Map OpenAPI Discriminator mapping's values to their real value in enums #3074
koxudaxi merged 5 commits into
koxudaxi:mainfrom
ilovelinux:fix/ilovelinux-3073-enum-literal-values

Conversation

@ilovelinux

@ilovelinux ilovelinux commented Apr 5, 2026

Copy link
Copy Markdown
Collaborator

Context

  • OpenAPI Discriminator mapping field is a key-value dictionary.
  • Both the keys and the values of the dictionary must be strings.
  • Despite they are strings, the mapping happens:
    1. Converting any received value to string.
    2. Comparing the converted value with the keys in the dictionary.

Ref: https://swagger.io/specification/#options-for-mapping-values-to-schemas

What's changed

  • Now mapping's keys are mapped to their real enum values, if available
  • Otherwise, old behavior kicks-in

Notes

Summary by CodeRabbit

  • Bug Fixes
    • Improved discriminator handling to correctly resolve and map multiple discriminator values, including numeric and float cases.
  • New Features
    • Optional behavior to use enum values in discriminator resolution for more accurate mappings.
  • Tests
    • Added regression tests covering integer/float discriminator mappings and the enum-value discriminator option.

Review Change Stack

@ilovelinux ilovelinux self-assigned this Apr 5, 2026
@coderabbitai

coderabbitai Bot commented Apr 5, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 79f4bcd6-b6ae-4115-b54c-ba7b989e1063

📥 Commits

Reviewing files that changed from the base of the PR and between a07509f and 3a53bf3.

⛔ Files ignored due to path filters (1)
  • tests/data/openapi/discriminator_float_mapping.yaml is excluded by !tests/data/**/*.yaml and included by none
📒 Files selected for processing (4)
  • src/datamodel_code_generator/parser/base.py
  • tests/data/expected/main/openapi/discriminator/float_mapping.py
  • tests/data/expected/main/openapi/discriminator/integer_mapping_use_enum.py
  • tests/main/openapi/test_main_openapi.py
💤 Files with no reviewable changes (1)
  • tests/main/openapi/test_main_openapi.py
✅ Files skipped from review due to trivial changes (1)
  • tests/data/expected/main/openapi/discriminator/integer_mapping_use_enum.py

📝 Walkthrough

Walkthrough

Refactors Parser discriminator resolution to support enum-member default values vs enum field names based on use_enum_values_in_discriminator, adds base-class enum lookup, and updates/adds generated expectation files and tests for integer and float discriminator mappings.

Changes

Discriminator handling and test fixtures

Layer / File(s) Summary
Parser: discriminator literal resolution & enum lookup
src/datamodel_code_generator/parser/base.py
Branches _create_discriminator_data_type on use_enum_values_in_discriminator, adds _get_enum_discriminator_literal, introduces get_enum_from_base() to scan base models for Enum, and unifies enum_source selection and call sites.
Generated expected: float mapping models
tests/data/expected/main/openapi/discriminator/float_mapping.py
Adds generated float-backed enums and models where discriminator Literals are stringified float values and a Base RootModel with discriminator='kind'.
Generated expected: integer mapping using enums
tests/data/expected/main/openapi/discriminator/integer_mapping_use_enum.py
Adds generated IntEnum-backed discriminator models used when --use-enum-values-in-discriminator is enabled.
Tests: OpenAPI discriminator regression tests
tests/main/openapi/test_main_openapi.py
Adds two regression tests asserting generation for integer-with-enum and float mapping discriminator YAML fixtures; tests skip on Black v19.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Suggested labels

breaking-change-analyzed, breaking-change

Suggested reviewers

  • koxudaxi

Poem

🐰
I found the enums beneath the sod,
Rescued numbers miscast as odd,
Field names or defaults, now we pick,
Discriminators fixed—click by click. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: mapping OpenAPI discriminator values to their real enum values instead of treating them as strings.
Linked Issues check ✅ Passed The PR successfully addresses issue #3073 by implementing logic to map discriminator values to real enum types, enabling integer Literals (Literal[2, 3]) instead of string Literals (Literal['2', '3']).
Out of Scope Changes check ✅ Passed All changes directly support the discriminator enum value mapping objective; no unrelated modifications were introduced beyond the stated scope.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codspeed-hq

codspeed-hq Bot commented Apr 5, 2026

Copy link
Copy Markdown

Merging this PR will improve performance by 14.76%

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 11 improved benchmarks
⏩ 98 skipped benchmarks1

Performance Changes

Mode Benchmark BASE HEAD Efficiency
WallTime test_perf_large_models_pydantic_v2 3.8 s 3.3 s +17.61%
WallTime test_perf_duplicate_names 1,087.4 ms 941.6 ms +15.48%
WallTime test_perf_complex_refs 2.2 s 1.9 s +15.19%
WallTime test_perf_deep_nested 5.5 s 4.8 s +15.8%
WallTime test_perf_multiple_files_input 3.8 s 3.3 s +15.51%
WallTime test_perf_openapi_large 3 s 2.6 s +14.98%
WallTime test_perf_all_options_enabled 5.9 s 5.2 s +14.19%
WallTime test_perf_kubernetes_style_pydantic_v2 2.7 s 2.4 s +12.74%
WallTime test_perf_graphql_style_pydantic_v2 847.4 ms 736.9 ms +15%
WallTime test_perf_stripe_style_pydantic_v2 2 s 1.8 s +10.86%
WallTime test_perf_aws_style_openapi_pydantic_v2 2 s 1.7 s +15.16%

Tip

Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.


Comparing ilovelinux:fix/ilovelinux-3073-enum-literal-values (3a53bf3) with main (35f7156)

Open in CodSpeed

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@codecov

codecov Bot commented Apr 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (5b66f67) to head (3a53bf3).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##              main     #3074    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           89        92     +3     
  Lines        18650     19363   +713     
  Branches      2156      2206    +50     
==========================================
+ Hits         18650     19363   +713     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ilovelinux

ilovelinux commented Apr 5, 2026

Copy link
Copy Markdown
Collaborator Author

This PR is draft because of the following tasks:

@ilovelinux ilovelinux marked this pull request as draft April 5, 2026 19:14
@ilovelinux ilovelinux changed the title Draft: Map OpenAPI Discriminator mapping's values to their real value in enums Map OpenAPI Discriminator mapping's values to their real value in enums Apr 5, 2026
@ilovelinux

Copy link
Copy Markdown
Collaborator Author

Hi, right now I don't have enough time to complete this PR. Feel free to adopt it, otherwise I should have more free time in june to complete steps described in #3074 (comment) 🤞

@kkinugasa since it's related to your issue, would you mind testing this PR and give us a feedback? Does it fix your issue? Thanks!

@koxudaxi koxudaxi force-pushed the fix/ilovelinux-3073-enum-literal-values branch 4 times, most recently from c9e9459 to ee22e3d Compare May 22, 2026 15:05
@koxudaxi koxudaxi force-pushed the fix/ilovelinux-3073-enum-literal-values branch from ee22e3d to 3a53bf3 Compare May 22, 2026 15:58
@koxudaxi koxudaxi marked this pull request as ready for review May 22, 2026 16:25
@koxudaxi

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 22, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@koxudaxi koxudaxi merged commit 4999c2b into koxudaxi:main May 22, 2026
43 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The PR's core behavioral change — resolving discriminator mapping keys to actual enum values — only affects the specific case of multiple discriminator mapping entries pointing to the same model with integer enum types. In that case, the old code generated string literals (e.g., Literal['2', '3']) which were non-functional and would fail Pydantic validation. The new code generates correct integer literals (Literal[2, 3]). Since the old output was already broken, no working user code is affected. For the common case (single mapping entry per model), the output is unchanged because get_discriminator_field_value() already resolved enum values before reaching _create_discriminator_data_type. The GenerationStore refactoring maintains backward compatibility: self.results is still a list (via subclass), and public function signatures (sort_data_models, sort_base_classes_for_mro) only add optional parameters with None defaults. Performance optimizations (_RenderedDataModelField caching, _has_field_statement, _get_unique_name) are behavior-preserving internal changes.


This analysis was performed by Claude Code Action

@github-actions

Copy link
Copy Markdown
Contributor

🎉 Released in 0.58.0

This PR is now available in the latest release. See the release notes for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OpenAPI integer discriminator with multiple enum values generates string Literals

2 participants